<%@ page import="com.party.core.model.system.TargetType" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="../../include/tag.jsp" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <title>主页管理</title>
    <%@include file="../../include/commonFile.jsp" %>
    <link rel="stylesheet" href="${ctx}/css/common/list.css">
    <link rel="stylesheet" href="${ctx}/static/uploadCI/upload.css">
    <link rel="stylesheet" href="${ctx}/css/ui/activity/publish_form.css">
    <link rel="stylesheet" href="${ctx}/css/ui/mall/store_form.css">
    <link rel="stylesheet" href="${ctx}/css/form-preview.css">
</head>
<body>
<!--头部-->
<%@include file="../../include/header.jsp" %>
<div class="index-outside">
    <%@include file="../../include/sidebar.jsp" %>
    <!--内容-->
    <section>
        <div class="section-main">
            <!-- 正文请写在这里 -->
            <div class="add-form-content">
                <form id="myForm" class="layui-form mt20" method="post" action="${ctx}/mall/store/save.do">
                    <div class="preview-box">
                        <div class="top-tip">
                            <span class="tip-inner"><span class="tip-title">效果预览</span></span>
                        </div>
                        <a class="preview-btn layui-btn layui-btn-danger layui-btn-sm" href="javascript:void(0)" lay-submit lay-filter="*">
                            <i class="iconfont icon-refresh btn-icon"></i>预览
                        </a>
                        <iframe style="width: 360px;height: 760px;" frameborder="0"
                                src="${ctx}/phone/preview.do?url=/shop/home/preview"></iframe>
                    </div>
                    <div class="form-outer">
                        <fieldset class="border mb10">
                            <legend>店铺基本信息</legend>
                            <div class="form-inner">
                                <input type="hidden" name="id" value="${mallStore.id}"/>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">店铺名称<span class="f-verify-red">*</span></label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="name" lay-verify="name" autocomplete="off"
                                               placeholder="店铺名称" class="layui-input" value="${mallStore.name}">
                                    </div>
                                    <a class="layui-btn  layui-btn-danger" href="javascript:txz.openQrDialog({
															title:'手机扫码访问店铺',
															detailList:[{
																title:'',
																url:'${qrCodeMap.qrCode}',
																link:'${qrCodeMap.qrCodeContent}'
															}]
														})"><i class="iconfont icon-qrcode btn-icon"></i>店铺推广</a>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">店铺Logo<span class="f-verify-red">*</span></label>
                                    <div class="cover-content">
                                        <input type="hidden" name="logo" id="logo" lay-verify="logo" value="${mallStore.logo}"/>
                                        <c:if test="${mallStore == null || empty mallStore.logo}">
                                            <span id="cover-img" class="round-img" style="background-image:url(${ctx}/image/posterImg.png)"></span>
                                        </c:if>
                                        <c:if test="${mallStore != null && not empty mallStore.logo}">
                                            <span id="cover-img" class="round-img" style="background-image:url('${mallStore.logo}')"></span>
                                        </c:if>
                                        <a class="layui-btn layui-btn-danger" id="sel_pic_img">+添加Logo</a>
                                        <%--<div class="form-word-aux">建议尺寸：800x450</div>--%>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">店铺简介</label>
                                    <div class="layui-input-block">
                                        <textarea name="about" placeholder="请输入店铺简介" lay-verify="about"
                                                  class="layui-textarea">${mallStore.about}</textarea>
                                    </div>
                                </div>
                            </div>
                        </fieldset>
                        <fieldset class="border mb10" style="width: 500px">
                            <legend>轮播图</legend>
                            <div class="form-inner" style="margin-right: 0">
                                <div class="carousel-list">
                                    <c:forEach var="carousel" items="${mallStore.carouselList}">

                                    </c:forEach>
                                    <div class="carousel-item">
                                        <div class="tc" style="padding: 5px">
                                            <div class="red carousel-add-btn">
                                                <i class="iconfont icon-add btn-icon"></i>
                                                <span style="vertical-align: sub">添加一张轮播图</span>
                                            </div>
                                            <div style="font-size: 13px; color: #bfbfbf">建议尺寸750*550像素&nbsp;&nbsp;&nbsp;&nbsp;最多可以添加5张轮播图,拖动可以调换顺序</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </fieldset>
                        <fieldset class="border mb10">
                            <legend>每日特惠</legend>
                            <div class="form-inner">
                                <div class="daily-deal-goods-list">
                                    <div class="upload-img-wrap goods-pic">
                                        <div class="upload-icon"
                                             onclick="addItem(this, 2, '选择商品', '${ctx}/mall/goods/selectGoods.do?isMulti=true', '790px', '710px')"
                                        > +
                                        </div>
                                    </div>
                                    <div class="cl"></div>
                                </div>
                            </div>
                        </fieldset>
                        <fieldset class="border mb10">
                            <legend>戈友推荐</legend>
                            <div class="form-inner">
                                <div class="friend-goods-list">
                                    <div class="upload-img-wrap goods-pic">
                                        <div class="upload-icon"
                                             onclick="addItem(this, 3, '选择商品', '${ctx}/mall/goods/selectGoods.do?isMulti=true', '790px', '710px')"
                                        > +
                                        </div>
                                    </div>
                                    <div class="cl"></div>
                                </div>
                            </div>
                        </fieldset>
                        <fieldset class="border mb10">
                            <legend>品牌推荐</legend>
                            <div class="form-inner">
                                <div class="brand-list">
                                    <div class="upload-img-wrap goods-pic">
                                        <div class="upload-icon"
                                             onclick="addItem(this, 5, '选择品牌', '${ctx}/mall/brand/selectBrand.do', '720px', '680px')"
                                        > +
                                        </div>
                                    </div>
                                    <div class="cl"></div>
                                </div>
                            </div>
                        </fieldset>
                        <fieldset class="border mb10">
                            <legend>分类商品导航</legend>
                            <div class="form-inner">
                                <a class="red mb10 db" href="javascript:selectCategoryGoods()">从商品分类中选择</a>
                                <div class="category-list"></div>
                                <div class="cl"></div>
                            </div>
                        </fieldset>
                        <div id="hiddenFieldDiv"></div>
                        <div id="hiddenCacheDiv">
                            <input type="hidden" name="_carouselArray" />
                            <input type="hidden" name="_dealArray" />
                            <input type="hidden" name="_friendArray" />
                            <input type="hidden" name="_brandArray" />
                            <input type="hidden" name="_categoryGoodsArray" />
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <a href="javascript:void(0)" class="layui-btn layui-btn-danger" lay-submit lay-filter="*">立即提交</a>
                                <a href="javascript:void(0)" class="layui-btn layui-btn-primary">取消</a>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <!--底部-->
        <%@include file="../../include/footer.jsp" %>
    </section>
    <div id="urlContent" style="display: none">
        <form class="layui-form p10" method="post" action="">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">链接地址<span class="f-verify-red">*</span></label>
                    <div class="layui-input-block">
                        <textarea name="url" class="layui-textarea" style="width: 250px; height: 100px"></textarea>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>
<!-- 轮播图 -->
<script type="text/html" id="carouselItem_template">
    <div class="carousel-item carousel-item-new" data-id="{{ d.id || '' }}" data-model="{{ d.model || '' }}"
         data-type="{{ d.type || '' }}" data-targetId="{{ d.targetId || '' }}">
        <div>
            <div class="l">
                <div class="upload-img-wrap">
                    {{# if(d.pic){ }}
                        <img src="{{ d.pic || '' }}" class="item-img"/>
                        <div class="upload-icon upload-icon-update">替换</div>
                    {{# }else{ }}
                        <img src="" class="item-img" style="display: none"/>
                        <div class="upload-icon"> +</div>
                    {{# } }}
                </div>
            </div>
            <div class="l" style="width: 75%">
                <div class="layui-form-item mb10">
                    <label class="layui-form-label">标题：<span class="f-verify-red">*</span></label>
                    <div class="layui-input-block">
                        <input type="text" lay-verify="title" autocomplete="off" class="layui-input carousel-title" value="{{ d.title || '' }}" />
                    </div>
                </div>
                <div class="layui-form-item" style="margin-bottom: 0">
                    <label class="layui-form-label">链接：<span class="f-verify-red">*</span></label>
                    <div class="layui-input-block url-div abs">
                        <a class="red expand add-btn" {{# if(d.resourceName){ }} style="display: none" {{# } }}>选择跳转到的页面&nbsp;<i class="iconfont icon-right"></i></a>
                        <div class="subject-content" {{# if(!d.resourceName){ }} style="display: none" {{# } }} >
                            {{# if(d.type == 4){ }}
                                <input type="hidden" class="carousel-url" value="{{d.resourceName }}" />
                            {{# } }}
                            <div class="category-style">
                                <div class="item-content">
                                    <span class="carousel-item-type">{{ d.typeName || '' }}</span>
                                    <span class="carousel-item-name ellipsis-1">{{ d.resourceName }}</span>
                                </div>
                                <span><i class="iconfont icon-close carousel-opt"></i></span>
                            </div>
                            <%--<a class="red expand update-btn" style="display: inline-block!important;">修改&nbsp;
                                <i class="iconfont icon-right"></i>
                            </a>--%>
                        </div>
                        <select class="layui-select" lay-filter="carousel-select">
                            <option value="zt">专题</option>
                            <option value="sp">商品及分类</option>
                            <option value="zdy">自定义链接</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="cl"></div>
        </div>
        <i class="icon-close-new" onclick="removeObj(this, '.carousel-item-new')"></i>
    </div>
</script>
<!-- 每日特惠、戈友推荐、品牌推荐 -->
<script type="text/html" id="goods_template">
    <div class="goods-pic target-item" data-id="{{ d.id || '' }}" data-targetId="{{ d.targetId || '' }}"
         data-type="{{ d.type || '' }}" data-model="{{ d.model || '' }}">
        <img src="{{ d.pic || '' }}">
        <i class="icon-close-new" onclick="removeObj(this, '.target-item')"></i>
    </div>
</script>
<!-- 分类导航 -->
<script type="text/html" id="category_template">
    <div class="category-item category-style" data-id="{{ d.id || '' }}" data-targetId="{{ d.targetId || '' }}"
         data-type="2" data-model="4" data-pId="{{ d.pId  || d.remarks || '' }}" >
        <div class="item-content">
            <span class="pName">{{ d.pName || '' }}</span>
            <span class="ellipsis-1 cName">{{ d.name || '' }}</span>
        </div>
        <span><i class="iconfont icon-close category-opt"></i></span>
    </div>
</script>
<script type="text/html" id="hiddenForm_template">
    <div class="hidden-field">
        <input type="hidden" name="resources[{{ d.index }}].id" value="{{ d.id }}"/>
        <input type="hidden" name="resources[{{ d.index }}].model" value="{{ d.model }}"/>
        <input type="hidden" name="resources[{{ d.index }}].title" value="{{ d.title }}"/>
        <input type="hidden" name="resources[{{ d.index }}].url" value="{{ d.url }}"/>
        <input type="hidden" name="resources[{{ d.index }}].targetId" value="{{ d.targetId }}"/>
        <input type="hidden" name="resources[{{ d.index }}].type" value="{{ d.type }}"/>
        <input type="hidden" name="resources[{{ d.index }}].sort" value="{{ d.sort }}"/>
        <input type="hidden" name="resources[{{ d.index }}].pic" value="{{ d.pic }}"/>
        <input type="hidden" name="resources[{{ d.index }}].remarks" value="{{ d.remarks }}"/>
    </div>
</script>
<script type="text/javascript" src="${ctx}/script/common/form_cache.js"></script>
<script src="${ctx}/script/form/jquery-1.12.4.js"></script>
<script src="${ctx}/script/form/jquery-ui.js"></script>
<script>
    var form, laytpl, formcache;
    $(function () {
        txz.initHeader({
            nav: [{
                name: '主页管理',
                curr: true
            }]
        });
        layui.use(['form', 'laytpl'], function () {
            form = layui.form, laytpl = layui.laytpl;
            //自定义验证规则
            form.verify({
                title: function (value) {
                    if (value.trim() == "") {
                        return '请填写店铺名称';
                    }
                },
                logo: function (value) {
                    if (value == "") {
                        return "请上传店铺Logo";
                    }
                }
            });
            if (util.isValid('${mallStore.id}')) {
                init();
            } else {
                //加载缓存
                formcache = new fCache({
                    fCacheKey: 'form_cache_store',//暂存的key
                    cacheCallback: loadCacheData,//获取到缓存后加载的方法
                    getFormData: getFormData
                }).init();
            }

            function init() {
                //loading层
                var loadIndex = layer.load(1, {
                    shade: [0.1, '#fff'] //0.1透明度的白色背景
                });
                txz.ajaxRequest({
                    method: 'post',
                    url: '${ctx}/mall/store/getStoreResource.do',
                    params: {"storeId": '${mallStore.id}'},
                    callBack: function (res) {
                        layer.close(loadIndex);
                        if (res.success) {
                            initCarousel(res.data.carouselList);
                            initCategory(res.data.categoryList);
                            initGoods('.daily-deal-goods-list', res.data.dailyDealList);
                            initGoods('.friend-goods-list', res.data.friendList);
                            initGoods('.brand-list', res.data.brandList);
                        } else {
                            util.layerMsgError('加载资源异常');
                        }
                    }
                });
            }

            //监听提交
            form.on('submit', function (data) {
                submitBefore(data);
            });

            // 轮播图 选择资源
            form.on('select(carousel-select)', function (data) {
                var optValue = data.value;
                if (optValue == "zt") { // 专题
                    selectSubject(data.elem);
                } else if (optValue == "sp") { // 商品及分类
                    selectGoodsCategory(data.elem);
                } else if (optValue == "zdy") { // 自定义链接
                    addUrl(data.elem);
                }
            });

            function submitBefore(data) {
                var flag = true;
                var $content = $("#hiddenFieldDiv");
                $content.html("");
                var getTpl = $("#hiddenForm_template").html();
                // 轮播图
                $(".carousel-list .carousel-item-new").each(function (index, ele) {
                    flag = renderHiddenField(ele, index, true);
                    return flag;
                });
                if (flag) {
                    // 每日特惠、戈友推荐、品牌推荐
                    $(".target-item").each(function (index, ele) {
                        renderHiddenField(ele, index, false);
                    });
                    // 分类导航
                    $(".category-item").each(function (index, ele) {
                        renderHiddenField(ele, index, false);
                    });

                    submitForm(data);
                }

                function renderHiddenField(ele, sort, openStatus) {
                    var checkFlag = true;
                    var title = $(ele).find(".carousel-title").val() || '';
                    var pic = $(ele).find("img").attr('src') || '';
                    var type = $(ele).attr("data-type");
                    var targetId = $(ele).attr("data-targetId") || '';
                    var url = $(ele).find(".carousel-url").val() || '';

                    if (openStatus) {
                        if (!util.isValid(title)) {
                            util.layerMsgError("标题不能为空");
                            checkFlag = false;
                            return false;
                        }
                        if (!util.isValid(pic)) {
                            util.layerMsgError("请选择图片");
                            checkFlag = false;
                            return false;
                        }
                        if (type == 4) {
                            if (!util.isValid(url)) {
                                util.layerMsgError("链接不能为空");
                                checkFlag = false;
                                return false;
                            }
                        } else {
                            if (!util.isValid(targetId)) {
                                util.layerMsgError("请选择要跳转的页面");
                                checkFlag = false;
                                return false;
                            }
                        }
                    }
                    var index = $(".hidden-field").length;
                    var map = {
                        index: index,
                        targetId: targetId,
                        model: $(ele).attr("data-model"),
                        type: type,
                        title: title,
                        url: url,
                        id: $(ele).attr("data-id"),
                        sort: sort + 1,
                        pic: pic,
                        remarks : $(ele).attr('data-pId') || ''
                    };
                    laytpl(getTpl).render(map, function (html) {
                        $content.append(html);
                    });
                    return checkFlag;
                }
            }

            function submitForm(data) {
                txz.submitObject(data.elem, function (callBack) {
                    var formData = getFormData();
                    var action = $("#myForm").attr("action");
                    txz.ajaxRequest({
                        method: 'post',
                        url: action,
                        saveCache: true,
                        cacheObj: formcache,
                        params: formData,
                        callBack: function (res) {
                            typeof callBack === 'function' && callBack();
                            if (res.success) {
                                util.layerMsgSuccess("提交成功", function () {
                                    location.reload();
                                });
                            } else {
                                util.layerMsgError(res.description)
                            }
                        }
                    });
                })
            }
        });

        // logo上传
        $('#sel_pic_img').click(function () {
            txz.openSelImg({
                min: 1,
                max: 1,
                info: '',
                type: '<%=TargetType.MALL.getCode()%>',
                cb: function (imgs) {
                    $('#cover-img').css('background-image', 'url(' + imgs[0].path + ')');
                    $('#logo').val(imgs[0].path);
                }
            })
        });

        // 添加轮播图
        $(".carousel-add-btn").click(function () {
            var childLength = $(".carousel-item-new").length;
            if (childLength == 5) {
                util.layerMsgError("最多只能添加5张");
                return false;
            }
            var $content = $(".carousel-item:last");
            var getTpl = $("#carouselItem_template").html();
            laytpl(getTpl).render({}, function (html) {
                $content.before(html);
            });
            form.render('select');
        });

        // 轮播图上传
        $(".carousel-list").on('click', '.upload-icon', function () {
            var $this = $(this);
            var $cover_img = $this.siblings("img"), $pic = $this.siblings("[name=pic]");
            txz.openSelImg({
                min: 1,
                max: 1,
                info: '建议尺寸：750x550',
                type: '<%=TargetType.MALL.getCode()%>',
                cb: function (imgs) {
                    $cover_img.attr('src', imgs[0].path);
                    $pic.val(imgs[0].path);
                    $cover_img.css('display', 'block');
                    $this.addClass("upload-icon-update");
                    $this.text("替换");
                }
            })
        });

        $(".carousel-list").delegate(" .carousel-opt", "click", function (e) {
            var $target = $(e.target);
            var $item = $target.closest(".carousel-item");
            $item.find(".subject-content").hide();
            $item.find(".add-btn").show();
            $item.attr("data-targetId", '');
            $item.attr("data-type", '');
            $item.attr("data-model", '');
        });

        $(".category-list").delegate(".category-opt", "click", function (e) {
            var $target = $(e.target);
            var $item = $target.closest(".category-item");
            $item.remove();
        });

        // 拖拽排序
        sortable();
        function sortable() {
            $(".carousel-list").sortable({
                items : ".carousel-item-new",
                placeholder: 'sortable-placeholder',
                opacity: 0.5,
                forcePlaceholderSize: true
            });
            $(".carousel-list").disableSelection();

            $(".daily-deal-goods-list").sortable({
                items : ".target-item",
                placeholder: 'sortable-placeholder',
                opacity: 0.5,
                forcePlaceholderSize: true
            });
            $(".daily-deal-goods-list").disableSelection();

            $(".friend-goods-list").sortable({
                items : ".target-item",
                placeholder: 'sortable-placeholder',
                opacity: 0.5,
                forcePlaceholderSize: true
            });
            $(".friend-goods-list").disableSelection();

            $(".brand-list").sortable({
                items : ".target-item",
                placeholder: 'sortable-placeholder',
                opacity: 0.5,
                forcePlaceholderSize: true
            });
            $(".brand-list").disableSelection();

            $(".category-list").sortable({
                items : ".category-item",
                placeholder: 'sortable-placeholder',
                opacity: 0.5,
                forcePlaceholderSize: true
            });
            $(".category-list").disableSelection();
        }
    });

    function getFormData() {
        // 轮播图
        var _carouselArray = new Array();
        $(".carousel-list .carousel-item-new").each(function (index, ele) {
            var map = {
                targetId: $(ele).attr("data-targetId") || '',
                model: $(ele).attr("data-model"),
                type: $(ele).attr("data-type"),
                title: $(ele).find(".carousel-title").val() || '',
                resourceName: $(ele).find(".carousel-title").val() || '',
                url: $(ele).find(".carousel-url").val() || '',
                id: $(ele).attr("data-id"),
                pic: $(ele).find("img").attr('src') || '',
                remarks: $(ele).attr('data-pId') || ''
            };
            _carouselArray.push(map);
        });
        $("#hiddenCacheDiv").find("[name=_carouselArray]").val(JSON.stringify(_carouselArray));

        // 每日特惠
        var _dealArray = formDataGoods('.daily-deal-goods-list');
        $("#hiddenCacheDiv").find("[name=_dealArray]").val(JSON.stringify(_dealArray));

        // 戈友推荐
        var _friendArray = formDataGoods('.friend-goods-list');
        $("#hiddenCacheDiv").find("[name=_friendArray]").val(JSON.stringify(_friendArray));

        // 品牌推荐
        var _brandArray = formDataGoods('.brand-list');
        $("#hiddenCacheDiv").find("[name=_brandArray]").val(JSON.stringify(_brandArray));

        // 商品分类
        var _categoryGoodsArray = new Array();
        $(".category-item").each(function (index, ele) {
            var map = {
                targetId: $(ele).attr("data-targetId") || '',
                model: $(ele).attr("data-model"),
                type: $(ele).attr("data-type"),
                parentName: $(ele).find(".item-content").find(".pName").text() || '',
                childName: $(ele).find(".item-content").find(".cName").text() || '',
                id: $(ele).attr("data-id"),
                pic: $(ele).find("img").attr('src') || '',
                remarks: $(ele).attr('data-pId') || ''
            };
            _categoryGoodsArray.push(map);
        });
        $("#hiddenCacheDiv").find("[name=_categoryGoodsArray]").val(JSON.stringify(_categoryGoodsArray));
        return util.serializeForm($('#myForm').serializeArray());
    }

    function formDataGoods(container) {
        var array = new Array();
        $(container).find(".target-item").each(function (index, ele) {
            var map = {
                targetId: $(ele).attr("data-targetId") || '',
                model: $(ele).attr("data-model"),
                type: $(ele).attr("data-type"),
                id: $(ele).attr("data-id"),
                pic: $(ele).find("img").attr('src') || ''
            };
            array.push(map);
        });
        return array;
    }

    //此方法用于加载缓存数据
    function loadCacheData(cacheData) {
        // logo
        if (cacheData['logo']) {
            $('#cover-img').css('background-image', 'url(' + cacheData['logo'] + ')');
        }
        // 轮播图
        if (cacheData['_carouselArray']) {
            var _carouselArray = eval(cacheData['_carouselArray']);
            for (var i = 0; i < _carouselArray.length; i++) {
                var _carousel = _carouselArray[i];
                var type = parseInt(_carousel['type']);
                var typeName = '';
                switch (type) {
                    case 1:
                        typeName = '专题';
                        break;
                    case 2:
                        typeName = '商品';
                        break;
                    case 3:
                        typeName = '分类';
                        break;
                    case 4:
                        typeName = '链接';
                        break;
                    case 5:
                        typeName = '品牌';
                        break;
                }
                _carousel['typeName'] = typeName;
            }
            $(".carousel-list .carousel-item-new").remove();
            initCarousel(_carouselArray);
        }

        $(".target-item").remove();
        // 每日特惠
        if (cacheData['_dealArray']) {
            var _dealArray = eval(cacheData['_dealArray']);
            initGoods('.daily-deal-goods-list', _dealArray);
        }
        // 每日特惠
        if (cacheData['_friendArray']) {
            var _friendArray = eval(cacheData['_friendArray']);
            initGoods('.friend-goods-list', _friendArray);
        }
        // 每日特惠
        if (cacheData['_brandArray']) {
            var _brandArray = eval(cacheData['_brandArray']);
            initGoods('.brand-list', _brandArray);
        }

        $(".category-item").remove();
        // 分类商品
        if (cacheData['_categoryGoodsArray']) {
            var _categoryGoodsArray = eval(cacheData['_categoryGoodsArray']);
            initCategory(_categoryGoodsArray);
        }
        form.render();
    }

    // 轮播图
    function initCarousel(data) {
        var $content = $(".carousel-item:last");
        var getTpl = $("#carouselItem_template").html();
        for (var i = 0; i < data.length; i++) {
            laytpl(getTpl).render(data[i], function (html) {
                $content.before(html);
            });
        }
        form.render('select');
    }

    // 分类
    function initCategory(data) {
        var $content = $(".category-list");
        var getTpl = $("#category_template").html();
        for (var i = 0; i < data.length; i++) {
            var obj = data[i];
            obj.pName = obj.parentName;
            obj.name = obj.childName;
            laytpl(getTpl).render(obj, function (html) {
                $content.append(html);
            });
        }
    }

    // 每日特惠、戈友推荐、品牌推荐
    function initGoods(content, data) {
        var $content = $(content).find(".goods-pic:last");
        var getTpl = $("#goods_template").html();
        for (var i = 0; i < data.length; i++) {
            laytpl(getTpl).render(data[i], function (html) {
                $content.before(html);
            });
        }
    }

    // 分类导航-选择分类商品（多选）
    function selectCategoryGoods() {
        function cb($jquery) {
            var datas = $($jquery.find("#selectDatas")).val();
            var dataObject = eval(datas);
            var $content = $(".category-list");
            var getTpl = $("#category_template").html();
            for (var i = 0; i < dataObject.length; i++) {
                var obj = dataObject[i];
                laytpl(getTpl).render(obj, function (html) {
                    $content.append(html);
                });
            }
        }

        openDialog('选择分类商品', '${ctx}/mall/goods/selectCategoryGoods.do', '', '650px', '550px', cb);
    }

    // 选择商品及分类（单选）
    function selectGoodsCategory(that) {
        function cb($jquery) {
            renderCarousel($jquery, that);
        }

        openDialog('选择商品或分类', '${ctx}/mall/goods/selectGoods.do', '', '790px', '710px', cb);
    }

    // 轮播图-选择专题（单选）
    function selectSubject(that) {
        function cb($jquery) {
            renderCarousel($jquery, that);
        }

        openDialog('选择专题', '${ctx}/mall/showsubject/selectSubject.do', '', '670px', '700px', cb);
    }

    // 每日特惠、戈友推荐、品牌推荐
    function addItem(target, model, title, url, width, height) {
        var $target = $(target);

        function cb($jquery) {
            var datas = $($jquery.find("#selectDatas")).val();
            var dataObject = eval(datas);
            var $content = $target.closest(".upload-img-wrap");
            var getTpl = $("#goods_template").html();
            for (var i = 0; i < dataObject.length; i++) {
                var obj = dataObject[i];
                obj.model = model;
                laytpl(getTpl).render(obj, function (html) {
                    $content.before(html);
                });
            }
        }

        openDialog(title, url, '', width, height, cb);
    }

    // 轮播图
    function renderCarousel($jquery, that) {
        var datas = $($jquery.find("#selectDatas")).val();
        var _result = (eval(datas))[0];
        var $item = $(that).closest(".carousel-item");
        if (_result.pic) {
            $item.find(".item-img").attr('src', _result.pic);
            $item.find(".item-img").show();
            $item.find(".upload-icon").addClass("upload-icon-update");
            $item.find(".upload-icon").text("替换");
        }
        $item.find(".carousel-title").val(_result.name);
        $item.attr("data-targetId", _result.targetId);
        $item.attr("data-type", _result.type);
        $item.attr("data-model", 1);
        $item.find(".add-btn").hide();
        $item.find(".subject-content").show();
        var typeName = '';
        if (_result.type == 1) {
            typeName = '专题';
        } else if (_result.type == 2) {
            typeName = '商品';
        } else if (_result.type == 3) {
            typeName = '分类';
        } else if (_result.type == 4) {
            typeName = '链接';
        }
        $item.find(".subject-content").find(".carousel-item-type").text(typeName);
        $item.find(".subject-content").find(".carousel-item-name").text(_result.name);


        if (_result.type != 4) {
            var length = $item.find(".subject-content").find(".carousel-url").length;
            if (length > 0) {
                $item.find(".subject-content").find(".carousel-url").remove();
            }
        }
    }

    // 轮播图-自定义链接
    function addUrl(that) {
        function cb(index) {
            var parse_url = /^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+$/;
            var link = $("#urlContent").find("[name=url]").val().trim();
            if (link == "") {
                util.layerMsgError("链接不能为空");
                return false;
            }
            if (!parse_url.test(link)) {
                util.layerMsgError("链接格式不正确");
                return false;
            }
            var $item = $(that).closest(".carousel-item");
            $item.attr("data-type", 4);
            $item.attr("data-model", 1);
            $item.find(".add-btn").hide();
            $item.find(".subject-content").show();
            $item.find(".subject-content").find(".carousel-item-type").text('链接');
            $item.find(".subject-content").find(".carousel-item-name").text(link);

            var length = $item.find(".subject-content").find(".carousel-url").length;
            if (length == 0) {
                $item.find(".subject-content .category-style").after('<input type="hidden" class="carousel-url" />');
            }
            $item.find(".subject-content").find(".carousel-url").val(link);
            $("#urlContent").find("[name=url]").val("");

            layer.close(index);
        }

        openDialog('自定义链接', '', '#urlContent', '450px', '250px', cb);
    }

    function removeObj(that, content) {
        $(that).closest(content).remove();
    }

    function openDialog(title, url, content, width, height, cb, target) {
        var index = layer.open({
            type: url ? 2 : 1,
            area: [width, height],
            title: title,
            maxmin: true, //开启最大化最小化按钮
            content: url || $(content),
            btn: ['确定', '关闭'],
            yes: function (index, layero) {
                if (content) {
                    cb(index);
                }
                if (url) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                    var inputForm = body.find('#inputForm');
                    var top_iframe;
                    if (target) {
                        top_iframe = target;//如果指定了iframe，则在改frame中跳转
                    } else {
                        top_iframe = '_parent';//获取当前active的tab的iframe
                    }
                    inputForm.attr("target", top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示

                    if (iframeWin.contentWindow.doSubmit()) {
                        cb(iframeWin.contentWindow.$);

                        setTimeout(function () {
                            top.layer.close(index);
                        }, 100);//延时0.1秒，对应360 7.1版本bug
                    }
                }
            },
            cancel: function (index) {
            }
        });
    }
</script>
</body>
</html>